package cn.com.common.job.task;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.com.common.constants.Constants;
import cn.com.gas.entity.GasAnalyseRegionRankingEntity;
import cn.com.gas.entity.GasAnalyseStationRankingEntity;
import cn.com.gas.entity.GasStationDeptEntity;
import cn.com.gas.entity.GasStationinfoEntity;
import cn.com.gas.entity.GasStaytimeResultEntity;
import cn.com.gas.service.GasAnalyseRegionRankingService;
import cn.com.gas.service.GasAnalyseStationRankingService;
import cn.com.gas.service.GasStationDeptService;
import cn.com.gas.service.GasStationinfoService;
import cn.com.gas.service.GasStaytimeResultService;
import cn.com.system.entity.SysDept;
import cn.com.system.service.DeptService;
import cn.com.util.TsBqUtils;

/**
 * 排行榜(区域、加油站) testTask为spring bean的名称， 方法名称必须是run
 *
 * @author wenbin
 * @version V1.0
 * @date 2024年4月18日
 */
@Component("gasAnalyseRankingProcessTask")
@DisallowConcurrentExecution
public class GasAnalyseRankingProcessTask {
	
	@Value("${gasstation.timedTask.gasAnalyseRankingProcessTask}")
	private String gasAnalyseRankingProcessTask;
	
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private GasStationinfoService gasStationinfoService;
	@Autowired
	private GasStaytimeResultService gasStaytimeResultService;
	@Autowired
	private GasAnalyseRegionRankingService gasAnalyseRegionRankingService;
	@Autowired
	private GasAnalyseStationRankingService gasAnalyseStationRankingService;
	@Autowired
	private DeptService deptService;
	@Autowired
	private GasStationDeptService gasStationDeptService;
	
	
	public void run(String params) throws Exception {
		logger.debug("gasAnalyseRankingProcessTask定时任务正在执行，参数为：{}", params);
		
		logger.debug("application参数为gasAnalyseRankingProcessTask：{}", gasAnalyseRankingProcessTask);

		if (gasAnalyseRankingProcessTask.equals(Constants.JOB_STOP)) {
			logger.debug("application配置文件控制不执行gasAnalyseRankingProcessTask定时任务");
			throw new Exception("application配置文件控制不执行gasAnalyseRankingProcessTask定时任务");
		}
		
		LocalDate now = LocalDate.now();
		LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
		LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());
		
		int year = now.getYear(); // 获取当前年份
		int month = now.getMonthValue(); // 获取当前月份
		String monthYear = handleMonthYear(month,year);

		if(TsBqUtils.isNotNull(params)){
			
			year = Integer.parseInt(params.substring(0, 4));
			month = Integer.parseInt(params.substring(4, 6));
			
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
		    LocalDate localDate = LocalDate.parse(params + "01", formatter);
		    
		    firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
		    firstDayOfNextMonth = localDate.with(TemporalAdjusters.firstDayOfNextMonth());
		    monthYear = params;
		    		
		}
		
		logger.debug("加工 当前月时间：{},{}", firstDayOfMonth, firstDayOfNextMonth);
		
		List<String> pid = new ArrayList<>();
		
		List<String> deptIdList = new ArrayList<>();
		List<GasStationDeptEntity> listGasStationDept = gasStationDeptService.list(Wrappers.lambdaQuery());
		if(TsBqUtils.isNotNull(listGasStationDept)){
			for (GasStationDeptEntity gasStationDeptEntity : listGasStationDept) {
				pid.add(gasStationDeptEntity.getEndangerId());
				
				deptIdList.add(gasStationDeptEntity.getDeptId());
			}
			
			
			LambdaQueryWrapper<GasStationinfoEntity> queryWrapper = Wrappers.lambdaQuery();

			queryWrapper.in(GasStationinfoEntity::getPid, pid);
			queryWrapper.eq(GasStationinfoEntity::getType, "group");
			queryWrapper.eq(GasStationinfoEntity::getIsAnalyse, "Y");

			List<GasStationinfoEntity> gasStationinfoList = gasStationinfoService.list(queryWrapper);

			for (GasStationinfoEntity gasStationinfoEntity : gasStationinfoList) {
				// 处理加油站 名称
				if (gasStationinfoEntity.getType().equals("group") || gasStationinfoEntity.getType().equals("domain")) {
					gasStationinfoEntity.setName(TsBqUtils.handleEndBeforeParentheses(gasStationinfoEntity.getName()));
				}

				// 计算累计金额
				BigDecimal result = new BigDecimal(0);
				String id = gasStationinfoEntity.getId();

				LambdaQueryWrapper<GasStaytimeResultEntity> queryWrapper1 = Wrappers.lambdaQuery();
				queryWrapper1.eq(GasStaytimeResultEntity::getStationId, id);
				// 当前月
				
				Date firstDayOfMonthDate = Date.from(firstDayOfMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
			    Date firstDayOfNextMonthDate = Date.from(firstDayOfNextMonth.atStartOfDay(ZoneId.systemDefault()).toInstant());
				queryWrapper1.ge(GasStaytimeResultEntity::getMessageDisappear, firstDayOfMonthDate);
				queryWrapper1.lt(GasStaytimeResultEntity::getMessageDisappear, firstDayOfNextMonthDate);
				
				List<GasStaytimeResultEntity> list = gasStaytimeResultService.list(queryWrapper1);
				int amountGasoline = 0;
				int amountDiesel = 0;
				
				for (GasStaytimeResultEntity gasStaytimeResultEntity : list) {
					String price = gasStaytimeResultEntity.getPrice();
					BigDecimal _price = new BigDecimal(price);
					result = result.add(_price);
					
					String oils = gasStaytimeResultEntity.getOils();
					if(oils.equals("汽油")){
						amountGasoline ++ ;
					}else{
						amountDiesel ++ ;
					}
					
				}
				
				gasStationinfoEntity.setPrice(result.toString());
				gasStationinfoEntity.setPriceBigDecimal(result);
				
				gasStationinfoEntity.setAmountGasoline(amountGasoline + "");
				gasStationinfoEntity.setAmountDiesel(amountDiesel + "");
				
			}
			
			
			// 对加油站 排名
			// 删除数据
			/*LambdaQueryWrapper<GasAnalyseStationRankingEntity> deleteWrapper = Wrappers.lambdaQuery();
			deleteWrapper.eq(GasAnalyseStationRankingEntity::getYearMonths, monthYear);
			gasAnalyseStationRankingService.remove(deleteWrapper);*/
			gasAnalyseStationRankingService.realRemoveByMonthYear(monthYear);
			
			
			// 排序保存
			Collections.sort(gasStationinfoList, (e1, e2) -> e2.getPriceBigDecimal().compareTo(e1.getPriceBigDecimal()));
			int i = 1;
			for (GasStationinfoEntity gasStationinfoEntity : gasStationinfoList) {
				
				GasAnalyseStationRankingEntity entity = new GasAnalyseStationRankingEntity();
				entity.setStationName(gasStationinfoEntity.getName());
				entity.setSale(gasStationinfoEntity.getPrice());
				entity.setRank(i);
				entity.setYearMonths(monthYear);
				entity.setTaxorgcode(gasStationinfoEntity.getTaxorgcode());
				entity.setStationId(gasStationinfoEntity.getId());
				entity.setDeleted(Constants.DATA_NOT_DELETED);
				
				entity.setAmountGasoline(gasStationinfoEntity.getAmountGasoline());
				entity.setAmountDiesel(gasStationinfoEntity.getAmountDiesel());
				
				entity.setCreateId("sys_job");
				entity.setCreateTime(Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant()));
				gasAnalyseStationRankingService.save(entity);
				i ++;
				
			}
			
			
			// 区域排行
			/*LambdaQueryWrapper<SysDept> queryWrapperDept = Wrappers.lambdaQuery();
			queryWrapperDept.eq(SysDept::getPid, "11305000000");
			List<SysDept> SysDept = deptService.list(queryWrapperDept);*/
			
			List<GasAnalyseRegionRankingEntity> regionRankingList = new ArrayList<GasAnalyseRegionRankingEntity>();
			
			List<String> _deptIdList = deptIdList.stream().distinct().collect(Collectors.toList());
			
			for (String taxorgcode : _deptIdList) {
				BigDecimal result = new BigDecimal(0);
				// String taxorgcode = dept.getId();
				LambdaQueryWrapper<GasAnalyseStationRankingEntity> queryWrapperGasAnalyseStationRanking = Wrappers.lambdaQuery();
				queryWrapperGasAnalyseStationRanking.eq(GasAnalyseStationRankingEntity::getTaxorgcode, taxorgcode);
				queryWrapperGasAnalyseStationRanking.eq(GasAnalyseStationRankingEntity::getYearMonths,monthYear);
				List<GasAnalyseStationRankingEntity> list = gasAnalyseStationRankingService.list(queryWrapperGasAnalyseStationRanking);
				
				for (GasAnalyseStationRankingEntity gasAnalyseStationRankingEntity : list) {
					String sale = gasAnalyseStationRankingEntity.getSale();
					BigDecimal _sale = new BigDecimal(sale);
					result = result.add(_sale);
				}
				
				GasAnalyseRegionRankingEntity entity = new GasAnalyseRegionRankingEntity();
				
				SysDept dept = deptService.getById(taxorgcode);
				entity.setRegionName(dept.getName());
				
				entity.setSale(result.toString());
				entity.setSaleBigDecimal(result);
				
				entity.setYearMonths(monthYear);
				entity.setTaxorgcode(taxorgcode);
				entity.setDeleted(Constants.DATA_NOT_DELETED);
				entity.setCreateId("sys_job");
				entity.setCreateTime(Date.from(now.atStartOfDay(ZoneId.systemDefault()).toInstant()));
				regionRankingList.add(entity);
			}
			
			// 删除数据
			/*LambdaQueryWrapper<GasAnalyseRegionRankingEntity> deleteWrapper1 = Wrappers.lambdaQuery();
			deleteWrapper1.eq(GasAnalyseRegionRankingEntity::getYearMonths, monthYear);
			gasAnalyseRegionRankingService.remove(deleteWrapper1);*/
			gasAnalyseRegionRankingService.realRemoveByMonthYear(monthYear);
			
			// 排序保存
			Collections.sort(regionRankingList, (a1, a2) -> a2.getSaleBigDecimal().compareTo(a1.getSaleBigDecimal()));
			int _i = 1;
			for (GasAnalyseRegionRankingEntity regionRankingEntity : regionRankingList) {
				
				regionRankingEntity.setRank(_i);
				gasAnalyseRegionRankingService.save(regionRankingEntity);
				
				_i ++;
				
			}
			
		}else{
			logger.error("GasStationDept表为配置数据");
		}
	}
	
	
	
	
	private static String handleMonthYear(int month, int year) {
		if (month <= 9) {
			return year + "0" + month;
		} else {
			return year + "" + month;
		}
	}
}
